package cn.vehicle.service.impl;

import cn.vehicle.domains.entity.VehicleTransportLedgerEntity;
import cn.vehicle.enums.InOutTypeEnum;
import cn.vehicle.enums.VehicleSnapshotTypeEnum;
import cn.vehicle.exception.VehicleAccessException;
import cn.vehicle.mapper.VehicleTransportLedgerMapper;
import cn.vehicle.service.VehicleTransportLedgerService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class VehicleTransportLedgerServiceImpl implements VehicleTransportLedgerService {

    @Resource
    private VehicleTransportLedgerMapper vehicleTransportLedgerMapper;
    @Override
    public void insert(VehicleTransportLedgerEntity vehicleTransportLedgerEntity) {
        vehicleTransportLedgerMapper.insertTransportLedger(vehicleTransportLedgerEntity);
    }

    @Override
    public void updateTransportExitInfo(VehicleTransportLedgerEntity vehicleTransportLedgerEntity) {
        vehicleTransportLedgerMapper.updateTransportExitInfo(vehicleTransportLedgerEntity);
    }

    @Override
    public void recordHeadMidTailImg(Long id, String inOutType, VehicleSnapshotTypeEnum vehicleSnapshotType, String url) {

        VehicleTransportLedgerEntity updateEntity = new VehicleTransportLedgerEntity();
        updateEntity.setId(id);

        if (InOutTypeEnum.IN.name().equals(inOutType)) {
            setEntryImg(updateEntity, url, vehicleSnapshotType);
        } else if (InOutTypeEnum.OUT.name().equals(inOutType)){
            setExitImg(updateEntity, url, vehicleSnapshotType);
        } else {
            throw VehicleAccessException.SYSTEM_ERROR.newInstance("unknown inOutType");
        }
        vehicleTransportLedgerMapper.updateTransportExitInfo(updateEntity);
    }

    @Override
    public VehicleTransportLedgerEntity getTransportLedgerById(Long id) {
        return vehicleTransportLedgerMapper.getTransportLedgerById(id);
    }


    private void setExitImg(VehicleTransportLedgerEntity updateEntity, String url, VehicleSnapshotTypeEnum vehicleSnapshotType) {
        switch (vehicleSnapshotType) {
            case HEAD -> updateEntity.setExitHeadImgUrl(url);
            case MID -> updateEntity.setExitMidImgUrl(url);
            case TAIL -> updateEntity.setExitTailImgUrl(url);
            default -> throw VehicleAccessException.SYSTEM_ERROR.newInstance("unknown vehicleSnapshotType");
        }
    }

    private void setEntryImg(VehicleTransportLedgerEntity updateEntity, String url, VehicleSnapshotTypeEnum vehicleSnapshotType) {
        switch (vehicleSnapshotType) {
            case HEAD -> updateEntity.setEntryHeadImgUrl(url);
            case MID -> updateEntity.setEntryMidImgUrl(url);
            case TAIL -> updateEntity.setEntryTailImgUrl(url);
            default -> throw VehicleAccessException.SYSTEM_ERROR.newInstance("unknown vehicleSnapshotType");
        }
    }
}
